/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.parser.mp.utils;

import com.alibaba.fastjson.JSONArray;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author Administrator
 */
public class TransformUtil {

    static private final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(TransformUtil.class.getName());

    public static long ipToLong(String ip) {
        if (StringUtils.isBlank(ip)) {
            return 0;
        }
        String[] ipArr = ip.split("\\.");
        if (ipArr.length != 4) {
            return 0;
        }
        long[] iplo = new long[4];
        iplo[0] = Long.parseLong(ipArr[0]);
        iplo[1] = Long.parseLong(ipArr[1]);
        iplo[2] = Long.parseLong(ipArr[2]);
        iplo[3] = Long.parseLong(ipArr[3]);
        return (iplo[0] << 24) + (iplo[1] << 16) + (iplo[2] << 8) + iplo[3];
    }

    public static long timeToLong(String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = sdf.parse(time);
        return date.getTime() / 1000;

    }

    /**
     *
     * @param time yyyy-MM-dd HH:mm:ss的时间转时间戳
     * @return
     */
    public static long stringTime2Long(String time) {
        long timestamp = -1;
        try {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sd.parse(time);
            timestamp = date.getTime();
        } catch (Exception e) {
            logger.error("(" + time + ")Type conversion error,cause " + e.getMessage(), e);
            logger.warn("@@" + time + ":" + timestamp);
        }
        return timestamp / 1000;
    }

    public static long strTime2Long(String time) {
        long timestamp = -1;
        try {
            SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = sd.parse(time);
            timestamp = date.getTime();
        } catch (Exception e) {
            logger.error("(" + time + ")Type conversion error,cause " + e.getMessage(), e);
            logger.warn("@@" + time + ":" + timestamp);
        }
        return timestamp / 1000;
    }

    public static String sort(String[] strs) {
//        String[] str = new String[]{"头条", "第三条", "头图", "首屏"};
        String[] s = new String[]{"头条", "第几条", "头图", "首屏"};
        StringBuilder result = new StringBuilder();
        for (String item : s) {
            for (String str : strs) {
                int len1 = item.length();
                int len2 = str.length();
                if ((item.substring(0, 1)).equals(str.substring(0, 1)) && (item.substring(len1 - 1, len1)).equals(str.substring(len2 - 1, len2))) {
                    result.append(str);
                    result.append(",");
                    break;
                }
            }
        }
        return result.substring(0, result.length() - 1);
    }

    public static String getWebNameById(String id, HashMap webname) {
        String name = "";
        for (Iterator columnsit = webname.entrySet().iterator(); columnsit.hasNext();) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) columnsit.next();
            if (entry.getKey().equals(id)) {
                name = entry.getValue();
                break;
            }
        }
        return name;
    }

    public static String getPorvinceIdByUserplace(String id, HashMap provincemap, HashMap placemap) {
        String provinceId = "";
        String name = "";
        for (Iterator columnsit = placemap.entrySet().iterator(); columnsit.hasNext();) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) columnsit.next();
            if (entry.getKey().equals(id)) {
                name = entry.getValue();
                for (Iterator columnsit2 = provincemap.entrySet().iterator(); columnsit2.hasNext();) {
                    Map.Entry<String, String> provinceEntry = (Map.Entry<String, String>) columnsit2.next();
                    if (entry.getValue().equals(name)) {
                        provinceId = provinceEntry.getKey();
                        break;
                    }
                }
                break;
            }
        }
        return provinceId;
    }

    public static String[] string2Strings(String str) {
        String[] strs = new String[]{};
        if (str == null || str.isEmpty() || str.equals("[]") || "null".equals(str)) {
//            logger.info("str is null or empty");
            strs = null;
        } else {
            try {
//                JSONArray jsonArray = JSONArray.parseArray(str);
                if (str.contains(",")) {

                    String[] jsonArray = str.substring(1, str.length() - 1).split(",");
                    strs = new String[jsonArray.length];
                    for (int k = 0; k < jsonArray.length; k++) {
                        String subject = jsonArray[k];
//                        logger.info(subject);
                        try {
                            strs[k] = new String(Base64.decodeFast(subject), "UTF-8");

                        } catch (Exception e) {
                            logger.error(e.getMessage(),e);
                            strs[k] = new String(Base64.decodeFast(""), "UTF-8");
                        }
                    }
                } else {
                    logger.info("str.substring(1, str.length() - 1)" + str.substring(1, str.length() - 1));
                    strs = new String[1];
                    strs[0] = str.substring(1, str.length() - 1);
                }
            } catch (Exception e) {
                logger.error("decode base64 or (string2Strings)Field segmentation failed, cause " + e.getMessage(), e);
                logger.warn("@@string2Strings Str:" + str + e.getMessage(), e);
            }
        }
        return strs;
    }

    /**
     * 针对图片宽度等数字字符串数组转换成数字数组
     *
     * @param arrayStr
     * @return
     */
    public static int[] stringToInts(String arrayStr) {
        if (arrayStr == null || arrayStr.isEmpty() || "null".equals(arrayStr) || "[]".equals(arrayStr)) {
            return null;
        }
        //去掉[]
        String[] strArray = arrayStr.substring(1, arrayStr.length() - 1).split(",");
        int[] intArray = new int[strArray.length];
        try {
            for (int j = 0; j < strArray.length; j++) {
                intArray[j] = Integer.parseInt(strArray[j]);
            }
        } catch (Exception e) {
            logger.error("transfer int to int[] fail" + e.getMessage(), e);
        }
        return intArray;
    }

    public static void main(String[] args) {
        String arrayStr = "[1,2,3]";
        int[] INTS = stringToInts(arrayStr);
        for (int i = 0; i < INTS.length; i++) {
            System.out.println(INTS[i]);
        }

    }
}
